package site.isscloud.web.controller.project;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import site.isscloud.common.core.controller.BaseController;
import site.isscloud.common.core.domain.AjaxResult;
import site.isscloud.project.domain.PjAlarmRecord;
import site.isscloud.project.service.IPjAlarmEventService;
import site.isscloud.project.service.IPjAlarmRecordService;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 告警模拟接收Controller（模拟MQTT数据接收）
 */
@RestController
@RequestMapping("/project/alarm/simulate")
public class AlarmSimulateController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(AlarmSimulateController.class);
    private static final Logger mqttLog = LoggerFactory.getLogger("mqtt");

    @Autowired
    private IPjAlarmRecordService alarmRecordService;

    @Autowired
    private IPjAlarmEventService alarmEventService;

    /**
     * 模拟接收MQTT告警数据
     * 该接口不需要token认证，在SecurityConfig中配置
     */
    @PostMapping("/receive")
    public AjaxResult receiveAlarm(@RequestBody Map<String, Object> alarmData) {
        try {
            mqttLog.info("=== 接收到模拟MQTT告警数据 ===");

            // 解析告警数据
            PjAlarmRecord alarmRecord = parseAlarmData(alarmData);
            if (alarmRecord == null) {
                return AjaxResult.error("告警数据解析失败");
            }

            mqttLog.info("设备: {}, 通道: {}, 类型: {}, 米标: {}, 断纤位置: {}, 温度: {}",
                    alarmRecord.getDeviceNo(), alarmRecord.getChanel(),
                    alarmRecord.getAlarmType(), alarmRecord.getMeterMark(),
                    alarmRecord.getFiberBreakPosition(), alarmRecord.getMeterAlarmTemperature());

            // 设置时间
            if (alarmRecord.getSCreateDatetime() == null) {
                alarmRecord.setSCreateDatetime(new Date());
            }
            if (alarmRecord.getCreateTime() == null) {
                alarmRecord.setCreateTime(new Date());
            }

            // 设置默认状态
            if (alarmRecord.getState() == null) {
                alarmRecord.setState(0); // 未处理
            }

            // 保存告警记录
            int result = alarmRecordService.insertPjAlarmRecord(alarmRecord);
            if (result > 0) {
                mqttLog.info("告警记录保存成功 - ID: {}", alarmRecord.getId());

                // 处理告警事件（复用已有的逻辑）
                alarmEventService.processAlarmRecord(alarmRecord);
                mqttLog.info("告警事件处理完成 - 记录ID: {}", alarmRecord.getId());

                return AjaxResult.success("告警接收处理成功");
            } else {
                mqttLog.error("告警记录保存失败");
                return AjaxResult.error("告警记录保存失败");
            }

        } catch (Exception e) {
            mqttLog.error("处理告警数据失败: {}", e.getMessage(), e);
            return AjaxResult.error("处理告警数据失败: " + e.getMessage());
        }
    }

    /**
     * 解析告警数据
     */
    private PjAlarmRecord parseAlarmData(Map<String, Object> alarmData) {
        try {
            PjAlarmRecord alarmRecord = new PjAlarmRecord();

            // 解析基础字段
            alarmRecord.setDeviceNo(getStringValue(alarmData, "deviceNo"));
            alarmRecord.setChanel(getIntegerValue(alarmData, "chanel"));
            alarmRecord.setAlarmType(getIntegerValue(alarmData, "alarmType"));
            alarmRecord.setState(getIntegerValue(alarmData, "state"));
            alarmRecord.setSData(getStringValue(alarmData, "sData"));

            // 根据告警类型解析特定字段
            Integer alarmType = alarmRecord.getAlarmType();
            if (alarmType == null) {
                mqttLog.error("告警类型不能为空");
                return null;
            }

            switch (alarmType) {
                case 1: // 断纤告警
                    alarmRecord.setFiberBreakPosition(getIntegerValue(alarmData, "fiberBreakPosition"));
                    alarmRecord.setMeterMark(null); // 断纤告警不需要米标
                    alarmRecord.setMeterAlarmTemperature(null);
                    alarmRecord.setMeterAlarmStatus(null);
                    alarmRecord.setLaserTemperature(null);
                    break;

                case 2: // 激光器故障
                    alarmRecord.setLaserTemperature(getIntegerValue(alarmData, "laserTemperature"));
                    alarmRecord.setFiberBreakPosition(null);
                    alarmRecord.setMeterMark(null);
                    alarmRecord.setMeterAlarmTemperature(null);
                    alarmRecord.setMeterAlarmStatus(null);
                    break;

                case 3: // 温度告警
                    alarmRecord.setMeterMark(getIntegerValue(alarmData, "meterMark"));
                    alarmRecord.setMeterAlarmTemperature(getBigDecimalValue(alarmData, "meterAlarmTemperature"));
                    alarmRecord.setMeterAlarmStatus(getIntegerValue(alarmData, "meterAlarmStatus"));
                    alarmRecord.setFiberBreakPosition(null);
                    alarmRecord.setLaserTemperature(null);
                    break;

                default:
                    mqttLog.error("不支持的告警类型: {}", alarmType);
                    return null;
            }

            // 验证必要字段
            if (!validateAlarmRecord(alarmRecord)) {
                return null;
            }

            return alarmRecord;

        } catch (Exception e) {
            mqttLog.error("解析告警数据异常: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * 验证告警记录的必要字段
     */
    private boolean validateAlarmRecord(PjAlarmRecord alarmRecord) {
        if (alarmRecord.getDeviceNo() == null || alarmRecord.getDeviceNo().trim().isEmpty()) {
            mqttLog.error("设备号不能为空");
            return false;
        }

        if (alarmRecord.getChanel() == null) {
            mqttLog.error("通道号不能为空");
            return false;
        }

        if (alarmRecord.getAlarmType() == null) {
            mqttLog.error("告警类型不能为空");
            return false;
        }

        // 根据告警类型验证特定字段
        switch (alarmRecord.getAlarmType()) {
            case 1: // 断纤告警
                if (alarmRecord.getFiberBreakPosition() == null) {
                    mqttLog.error("断纤告警必须包含断纤位置");
                    return false;
                }
                break;

            case 2: // 激光器故障
                if (alarmRecord.getLaserTemperature() == null) {
                    mqttLog.error("激光器故障告警必须包含激光器温度");
                    return false;
                }
                break;

            case 3: // 温度告警
                if (alarmRecord.getMeterMark() == null) {
                    mqttLog.error("温度告警必须包含米标");
                    return false;
                }
                if (alarmRecord.getMeterAlarmTemperature() == null) {
                    mqttLog.error("温度告警必须包含温度值");
                    return false;
                }
                break;
        }

        return true;
    }

    /**
     * 从Map中获取字符串值
     */
    private String getStringValue(Map<String, Object> data, String key) {
        Object value = data.get(key);
        return value != null ? value.toString() : null;
    }

    /**
     * 从Map中获取整数值
     */
    private Integer getIntegerValue(Map<String, Object> data, String key) {
        Object value = data.get(key);
        if (value == null) {
            return null;
        }
        if (value instanceof Integer) {
            return (Integer) value;
        }
        try {
            return Integer.parseInt(value.toString());
        } catch (NumberFormatException e) {
            mqttLog.warn("字段 {} 的值 {} 无法转换为整数", key, value);
            return null;
        }
    }

    /**
     * 从Map中获取BigDecimal值
     */
    private java.math.BigDecimal getBigDecimalValue(Map<String, Object> data, String key) {
        Object value = data.get(key);
        if (value == null) {
            return null;
        }
        if (value instanceof java.math.BigDecimal) {
            return (java.math.BigDecimal) value;
        }
        try {
            return new java.math.BigDecimal(value.toString());
        } catch (NumberFormatException e) {
            mqttLog.warn("字段 {} 的值 {} 无法转换为BigDecimal", key, value);
            return null;
        }
    }

    /**
     * 接收原始JSON字符串（兼容性接口）
     */
    @PostMapping("/receiveRaw")
    public AjaxResult receiveAlarmRaw(@RequestBody String rawData) {
        try {
            mqttLog.info("接收到原始告警数据: {}", rawData);

            // 这里可以添加JSON解析逻辑
            // 暂时返回错误，建议使用/receive接口
            return AjaxResult.error("请使用 /receive 接口，提供结构化的告警数据");

        } catch (Exception e) {
            mqttLog.error("处理原始告警数据失败: {}", e.getMessage(), e);
            return AjaxResult.error("处理原始告警数据失败: " + e.getMessage());
        }
    }
}